package com.viboo.concern.util;

import com.google.gson.Gson;
import com.viboo.concern.entity.ChatToken;
import com.viboo.concern.response.ResultEnum;
import com.viboo.concern.response.WeChatToken;
import com.viboo.concern.service.impl.TokenServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

/**
 * @author avanline
 * @descriotion
 * @date 2018-03-07 9:28
 */
@Slf4j
@Component
public class WeChatUtil {

    @Autowired
    TokenServiceImpl tokenService;

    private static WeChatUtil weChatUtil;  // 关键2

    @PostConstruct
    public void init() {
        weChatUtil = this;
    }

    /**
     * 获取  JS-SDK Access_token
     *
     * @return
     * @throws BaseException
     */
    public static String getToken() throws BaseException {
        ChatToken chatToken = weChatUtil.tokenService.selectByPrimaryKey(Constants.APP_ID);
        if (chatToken != null && chatToken.getExpiresIn() > System.currentTimeMillis() / 1000) {
            return chatToken.getAccessToken();
        }
        String url = "https://api.weixin.qq.com/cgi-bin/token";
        Map<String, String> map = new HashMap<>();
        map.put("appid", Constants.APP_ID);
        map.put("secret", Constants.APP_SECRET);
        map.put("grant_type", "client_credential");
        String mValue = NetHttpClient.sendGet(url, map);
        WeChatToken mTokenBean = new Gson().fromJson(mValue, WeChatToken.class);
        if (mTokenBean == null) {
            throw new BaseException(ResultEnum.SERVICE_ERROR.getCode(), mValue);
        }
        ChatToken mChatToken = new ChatToken();
        mChatToken.setAccessToken(mTokenBean.access_token);
        mChatToken.setAppId(Constants.APP_ID);
        if (chatToken != null) {
            log.info("token_http:{},{}", chatToken.getExpiresIn(), System.currentTimeMillis() / 1000);
            weChatUtil.tokenService.updateByPrimaryKey(mChatToken);
        } else {
            weChatUtil.tokenService.insert(mChatToken);
        }
        return mTokenBean.access_token;
    }
}
